package com.xiaochun.hxhj;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.myview.CustomProgressDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.util.DensityUtil;
import com.util.ExitAppUtil;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ShareUtil;
import com.util.StatusBarUtil;
import com.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog.Builder;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

//商城

public class WebviewActivity extends BaseActivity implements View.OnClickListener {


    private com.tencent.smtt.sdk.WebView webview;
    private CustomProgressDialog customProgressDialog;
    private RelativeLayout errorview;
    private boolean loadError = false;
    private IWXAPI api;
    private WebSettings webSettings;
    private String shopurl;
    private String paymessage = "";
    private Dialog downloadDialog;
    private Thread downLoadThread;
    private String apkurl = "";

    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;
    private static final int DOWN_ERROR = 4;
    private int progress;
    private ProgressBar mProgress;
    private Dialog noticeDialog;
    private Uri photoUri;
    private Uri photoUricat;
    private String UppicPath;

    private File imgFile;
    private boolean is_shot;//是否来源于拍照
    private String userlogoupload;
    private String title;
    private String desc;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLog.e("网页网特", "网页网特22222");
        StatusBarUtil.transparencyBar(this); //设置状态栏全透明
        StatusBarUtil.StatusBarLightMode(this); //设置白底黑字
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initView() {

//        EventBus.getDefault().register(this);

        changeTitle("");
        webview = findViewById(R.id.webview);
        String token = getUserInfo("token");
        shopurl = getIntent().getStringExtra("url");
//        shopurl = shopurl+"&token="+token;
//        String shopurl = getUserInfo("shopurl");
        errorview = findViewById(R.id.online_error_btn_retry);

        //支持缩放，默认为true。
        webSettings = webview.getSettings();
        webSettings.setUseWideViewPort(true); // 缩放至屏幕的大小 webSettings
        webSettings.setLoadWithOverviewMode(true); //设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8"); ////设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setJavaScriptEnabled(true);// 设置可以运行JS脚本
        webSettings.setSupportZoom(false);// 用于设置webview放大
        webSettings.setBuiltInZoomControls(false);


        webSettings.setDomStorageEnabled(true);

        /*if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {

            webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//            webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webview.getSettings().setBlockNetworkImage(false);*/

        //支持js
        webSettings.setJavaScriptEnabled(true);
        //设置本地调用对象及其接口
        webview.addJavascriptInterface(new Waimairenjsobj(), "h5_android");
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //在这里执行你想调用的js函数
                if (loadError != true) {
                    errorview.setVisibility(View.GONE);
                    webview.setVisibility(View.VISIBLE);
                }


            }


            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(webView, webResourceRequest, webResourceError);
                if (customProgressDialog != null) {
                    if (customProgressDialog.isShowing()) {
                        customProgressDialog.dismiss();
                    }
                }
                webView.setVisibility(View.GONE);
                errorview.setVisibility(View.VISIBLE);
                loadError = true;
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
//                hideErrorPage();
//                showErrorPage();
                if (customProgressDialog != null) {
                    if (customProgressDialog.isShowing()) {
                        customProgressDialog.dismiss();
                    }
                }
                webView.setVisibility(View.GONE);
                errorview.setVisibility(View.VISIBLE);
                loadError = true;

            }
        });
//        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);


        //3、 加载需要显示的网页
        webview.loadUrl(shopurl);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (customProgressDialog != null) {
                        if (customProgressDialog.isShowing()) {
                            customProgressDialog.dismiss();
                        }
                    }
                }
            }
        });

    }

    private final class Waimairenjsobj {
        // 打电话
        @JavascriptInterface
        public void reback() {
            finish();
        }

        @JavascriptInterface
        public void choose(String str) {
            if (!"".equals(str)) {
                String data = str;
                Log.e("地址点击条目", str + "   WebviewForMineActivity条目");

                Intent intent = new Intent();
                intent.putExtra("addressinfo", data);
                setResult(RESULT_OK, intent);
                finish();

            }
        }

        @JavascriptInterface
        public void call(String phone) {
            //TODO  通过sp中获取mobile
            String kefuphone = "";
            try {
                JSONObject obj = new JSONObject(phone);
                kefuphone = obj.getString("phone");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MyLog.e("联系电话", phone + "     kefuphone=" + kefuphone);
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + phone);
            intent.setData(data);
            startActivity(intent);
        }

        @JavascriptInterface
        public void callPhone(String phone) {
            //TODO  通过sp中获取mobile
            String kefuphone = "";
            try {
                JSONObject obj = new JSONObject(phone);
                kefuphone = obj.getString("phone");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MyLog.e("联系电话", phone + "     kefuphone=" + kefuphone);
            Intent intent = new Intent(Intent.ACTION_DIAL);
            Uri data = Uri.parse("tel:" + kefuphone);
            intent.setData(data);
            startActivity(intent);
        }

        @JavascriptInterface
        public void logout() {
            logoutUser();

        }

        @JavascriptInterface
        public void goLogin() {
            MyLog.e("H5需登陆", "   H5需登陆");
            Intent intent = new Intent(context, LoginActivity.class);
            startActivity(intent);
        }

        @JavascriptInterface
        public void pullPay(String paycontent) {
            MyLog.e("微信支付参数", paycontent + "   参数");
            gopay(paycontent);
        }

        @JavascriptInterface
        public void shareWx() {
            //学习报告分享好友
            //title   慧学记
            //desc  快来与我一起学习吧
            //link   https://f-m.bigchun.com/h5/index.html#/wx
            //img   桌面logo

            sharedata();


        }

        @JavascriptInterface
        public void setRemind(String string) {
            //课程提醒
            MyLog.e("课程提醒", string + "  状态和时间");

//            String isopentixing = sharedPreferences.getString("isopentixing", "1");
//            String tixingtime = sharedPreferences.getString("tixingtime", "08:00");
            //{"switch":false,"time":"08:00"}
            try {
                JSONObject obj = new JSONObject(string);
                String switchstr = obj.getString("switch");
                String time = obj.getString("time");
                String isopen = "";
                if ("false".equals(switchstr)) {
                    isopen = "0";
                } else {
                    isopen = "1";
                }
                saveUserInfo("isopentixing", isopen);
                saveUserInfo("tixingtime", time);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @JavascriptInterface
        public void goCourse(String string) {
            //课程提醒
            String id = "";
            try {
                JSONObject obj = new JSONObject(string);
                id = obj.getString("id");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MyLog.e("已开课和去复习", string + "  已开课和去复习");
            Intent intent = new Intent(context, MyCourseActivity.class);
            intent.putExtra("id", id);
            startActivity(intent);
        }

        @JavascriptInterface
        public void saveImg(String string) {
            //课程提醒
            MyLog.e("保存老师二维码", string + "  保存老师二维码图片");
            String imgutl = "";
            try {
                JSONObject obj = new JSONObject(string);
                imgutl = obj.getString("url");
            } catch (JSONException e) {
                e.printStackTrace();
            }


            Bitmap bitmap = decodeUriAsBitmapFromNet(imgutl);
            saveImageToGallery(context, bitmap);

        }

        @JavascriptInterface
        public void appVersion() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //课程提醒
                    String versionName = "";
                    try {
                        versionName = getVersionName();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    MyLog.e("版本更新", versionName + "  版本更新");
                    webSettings.setJavaScriptEnabled(true);
                    webview.loadUrl("javascript:getVersion('" + versionName + "')");
                }
            });
        }

        @JavascriptInterface
        public void postVersion(String string) {
            //课程提醒
            MyLog.e("版本更新下载地址", string + "  版本更新下载地址");
            apkurl = string;
            showDownloadDialog();
        }

        @JavascriptInterface
        public void postImage() {
            //课程提醒
            MyLog.e("更新头像", "  更新头像");

            changeUserLogo();
        }

        @JavascriptInterface
        public void saveStatus(String str) {
            //用户头像   1成功   0失败
            MyLog.e("更新头像", str + "  更新头像成功失败");

            if ("1".equals(str)) {
                saveUserInfo("avatar", userlogoupload);
            }
        }

        @JavascriptInterface
        public void postName(String str) {

            MyLog.e("更新昵称", str + "  更新昵称");

            saveUserInfo("nickname", str);
        }

        @JavascriptInterface
        public void postPhone(String str) {
            //用户头像   1成功   0失败
            MyLog.e("更新手机号", str + "  更新手机号");

            saveUserInfo("mobile", str);
        }

    }

    /**
     * 根据图片的url路径获得Bitmap对象
     *
     * @param url
     * @return
     */
    private Bitmap decodeUriAsBitmapFromNet(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;

        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "BianMin");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = "sign_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        String path = file.getAbsolutePath();
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), path, fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        Toast.makeText(context, "保存成功", Toast.LENGTH_LONG).show();
    }

    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    public void gopay(String content) {
//        {"appid":"wx51d9f7800e331c72","partnerid":"1231688202","prepayid":"wx12164426508371820365563b1906338400","timestamp":"1591951439","noncestr":"ORjyLSdWBZ1Dpufn","package":"Sign=WXPay","sign":"312A4E3B96545CB4D55C16D49B600BCF"}

        String pay_status = myapp.getPay_status();
        if ("1".equals(pay_status)) {
            //开启


            try {
                JSONObject obj = new JSONObject(content);
//                String appid = obj.getString("appid");
                String appid = myapp.getAppId();
                String partnerid = obj.getString("partnerid");
                String prepayid = obj.getString("prepayid");
                String timestamp = obj.getString("timestamp");
                String noncestr = obj.getString("noncestr");
                String packagewx = obj.getString("package");
                String sign = obj.getString("sign");

                PayReq req = new PayReq();

                req.appId = appid;
                req.partnerId = partnerid;
                req.prepayId = prepayid;
                req.nonceStr = noncestr;
                req.timeStamp = timestamp;
                req.packageValue = packagewx;
                req.sign = sign;
                //req.extData = "app data"; // optional
                ToastUtils.show("支付中");
                // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信

                api = WXAPIFactory.createWXAPI(context, req.appId);
                api.registerApp(req.appId);
                api.sendReq(req);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if ("0".equals(pay_status)) {
            //关闭
            ToastUtils.show(myapp.getPay_status_msg());
        }

    }

    @Override
    protected void onPause() {
        webview.reload();

        super.onPause();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        errorview.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                customProgressDialog.show();
                loadError = false;
                webview.reload();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }


    }


    public final void showLongToast(final String msg) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        });
    }


    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 2:
                    saveUserInfo("user_id", "");
                    saveUserInfo("username", "");
                    saveUserInfo("nickname", "");
                    saveUserInfo("mobile", "");
                    saveUserInfo("avatar", "");
                    saveUserInfo("score", "");
                    saveUserInfo("student_id", "");
                    saveUserInfo("is_bind_wx", "");
                    saveUserInfo("token", "");
                    saveUserInfo("is_agent", "");
                    saveUserInfo("vip_expire", "");
                    saveUserInfo("is_vip", "");
                    finish();
                    break;
                case 3:

                    String obj = (String) msg.obj;
//                    ToastUtils.show(obj);
                    MyLog.e("分享的积分重新加载", shopurl + "   链接");
                    webview.loadUrl(shopurl);

                    //1成功   0失败
                    String strs = "1";
                    webSettings.setJavaScriptEnabled(true);
                    webview.loadUrl("javascript:getStatus('" + strs + "')");

                    break;
                case 4:

                    /*String imgurl = (String) msg.obj;
                    GlideUtils.loadCircleImage(getApplicationContext(),imgurl,img_userlogi);
                    userlogoImgUrl = imgurl;*/
                    break;
                case 5:
                    String strstr = (String) msg.obj;
                    userlogoupload = strstr;
                    Log.e("----------", "============" + strstr);
                    webSettings.setJavaScriptEnabled(true);
                    webview.loadUrl("javascript:getImage('" + strstr + "')");
                    break;

                case 0:
                    String str = (String) msg.obj;
//                    ToastUtils.show(str);
                    break;
                case 1:
//                    ToastUtils.show("网络错误");
                    break;
                case 6:
                    /*//保存成功
                    saveUserInfo("username",nicknamesave);
                    saveUserInfo("nickname",nicknamesave);
                    saveUserInfo("avatar",userlogoImgUrl);
                    showToast("信息保存成功");

                    finish();*/

                    break;

                case 11:
                    saveUserInfo("user_id", "");
                    saveUserInfo("username", "");
                    saveUserInfo("nickname", "");
                    saveUserInfo("mobile", "");
                    saveUserInfo("avatar", "");
                    saveUserInfo("score", "");
                    saveUserInfo("student_id", "");
                    saveUserInfo("is_bind_wx", "");
                    saveUserInfo("token", "");
                    saveUserInfo("is_agent", "");
                    saveUserInfo("vip_expire", "");
                    saveUserInfo("is_vip", "");
                    finish();
                    break;
                case 31:
                    Log.e("分享好友", "   分享好友");
                    String user_id = getUserInfo("user_id");
                    String appid = myapp.getAppId();
//                String url = "https://www.seeland-wood.com/index/material/detail?id=13614";
                    String url = myapp.getSiteurlweb() + "/index.html#/wx?pid=" + user_id;
//                    String title1 = ti;
//                    String description = "快来与我一起学习吧";
//                String description = store_info;
//                String url = "zyt://app/openwith?id=20181015";
                    Log.e("分享链接", url + "   链接  user_id=" + user_id);
                    Log.e("分享链接title", title + "   链接");
                    Log.e("分享链接description", desc + "   链接");
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                    ShareUtil.shareToweixin(WebviewActivity.this, url, title, desc, bitmap, appid);
                    shareForScore();
                    break;
            }
            switch (msg.what) {
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    MyLog.i("ssssssssssssss", "sssssdddddddd");
                    installApk();
                    break;
                case DOWN_ERROR:
                    showNoticeErrorDialog();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 重写onKeyDown，当浏览网页，WebView可以后退时执行后退操作。
     * false 执行安卓返回方法即webview返回上一页 true 表示h5处理返回事件，android端不再处理
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            webview.evaluateJavascript("javascript:_Native_backListener()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    if ("false".equals(value) || "null".equals(value)) {
                        Log.e("执行安卓返回方法", "  ...");
                        goBack();
                    } else if ("true".equals(value)) {
                        // h5处理，客户端不做任何操作
                        Log.e("h5处理，客户端不做任何操作", "ddd");
                    }
                }
            });
        }
        return true;
    }

    private void goBack() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (shopurl.contains("kcxiangqing")) {
            String id = getIntent().getStringExtra("id");
            String token = getUserInfo("token");
            String str = myapp.getSiteurlweb() + "/#/kcxiangqing?id=" + id + "&token=" + token;
            if (paymessage.contains("微信支付") || paymessage.contains("用户取消支付")) {

            } else {
                webview.loadUrl(str);
            }
            MyLog.e("网页", token + "   onResume     " + str);
            webSettings.setJavaScriptEnabled(true);
            webview.loadUrl("javascript:gettoken('" + token + "')");
        } else if (shopurl.contains("integral")) {
            webview.loadUrl(shopurl);

        }
        MyLog.e("网页", "   onResume     ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
       /* if (webview !=null){

            webview.stopLoading();

            webview.getSettings().setJavaScriptEnabled(false);

            webview.clearHistory();

            webview.clearView();

            //mWebView = null;

        }*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(InfoEventMessage event) {
        paymessage = event.getMessage();
        webSettings.setJavaScriptEnabled(true);
        //0失败   1成功

        String sr = "";
        if ("微信支付成功".equals(paymessage)) {
//            ToastUtils.show("微信支付成功");
            Log.e("GTPCmessage--new--order", paymessage);
            sr = "1";
            webview.loadUrl("javascript:getStatus('" + sr + "')");
            MyLog.e("网页", "   EVENTBUS     ");
        } else if ("微信支付失败".equals(paymessage)) {
//            ToastUtils.show("微信支付失败");
            Log.e("GTPCmessage--new--order", paymessage);
            sr = "0";
            webview.loadUrl("javascript:getStatus('" + sr + "')");
            MyLog.e("网页", "   EVENTBUS     ");
        } else if ("用户取消支付".equals(paymessage)) {
//            ToastUtils.show("用户取消支付");
            Log.e("GTPCmessage--new--order", paymessage);
            sr = "0";
            webview.loadUrl("javascript:getStatus('" + sr + "')");
            MyLog.e("网页", "   EVENTBUS     ");
        } else if ("分享得积分".equals(paymessage)) {
        }else if ("设备ID已更新退出登录".equals(paymessage)){
            String type = event.getType();
            ExitAppUtil.getInstance().popbyexit(type,context,WebviewActivity.this,webview);
//            popbyexit(type);
        }


    }


    private void showDownloadDialog() {
        Builder builder = new Builder(new ContextThemeWrapper(context, R.style.AlertDialogCustom));
        builder.setTitle(context.getString(R.string.soft_upload));
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);

        builder.setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });

        builder.setView(v);


        downloadDialog = builder.create();
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.setCancelable(false);//可选,点击返回键无效

        downloadDialog.show();

        downloadApk();
    }

    /**
     * 下载apk
     */

    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private static String savePath = "/sdcard/updatedemo/";

    private static String saveFileName = savePath + "UpdateDemoRelease.apk";
    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {

                URL url = new URL(apkurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("Accept-Encoding", "identity");
                conn.connect();
                if (conn.getResponseCode() == 200) {
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    savePath = Environment.getExternalStorageDirectory().getPath() + "/update";
                    String[] command = {"chmod", "777", savePath};
                    ProcessBuilder builder = new ProcessBuilder(command);
                    try {
                        builder.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    File file = new File(savePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    saveFileName = savePath + "UpdateDemoRelease.apk";
                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                    MyLog.i("aaaaaaaaaaa", "sssssssssssss");
                    int count = 0;
                    byte buf[] = new byte[1024];

                    do {
                        int numread = is.read(buf);
                        if (numread <= 0) {
                            //下载完成通知安装
                            MyLog.e("下载完成", "开始安装");
                            handler.sendEmptyMessage(DOWN_OVER);
                            break;
                        }
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        //更新进度
                        MyLog.e("下载中", "numread=" + numread + "   count=" + count + "    progress=" + progress);
                        handler.sendEmptyMessage(DOWN_UPDATE);

                        fos.write(buf, 0, numread);
                    } while (!interceptFlag);//点击取消就停止下载.
                    fos.close();
                    is.close();
                } else {
                    handler.sendEmptyMessage(DOWN_UPDATE);
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };
    private boolean interceptFlag = false;

    /**
     * 安装apk
     */
    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        SharedPreferences userInfo = context.getSharedPreferences("Appset", Activity.MODE_PRIVATE);
        userInfo.edit().putString("appdataver", "0").commit();
        Intent i = new Intent(Intent.ACTION_VIEW);
        Uri data = Uri.fromFile(apkfile);
        if (Build.VERSION.SDK_INT >= 24) {
            data = FileProvider.getUriForFile(context, "com.xiaochun.hxhj.fileprovider", apkfile);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(apkfile);
        }
        i.setDataAndType(data, "application/vnd.android.package-archive");
        context.startActivity(i);


    }

    private void showNoticeErrorDialog() {
        Builder builder = new Builder(context);
        builder.setTitle(context.getString(R.string.soft_upload));
        builder.setMessage(context.getString(R.string.data_lost_retry));

        builder.setNegativeButton(context.getString(R.string.next_time_say), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.show();
    }

    private void logoutUser() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/user/logout";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
//        paramsMap.put("token", token);
        MyLog.e("退出登录", token + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }

                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void shareForScore() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/Leesign/share_incre_num";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
//        paramsMap.put("token", token);
        MyLog.e("分享得积分", token + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    String msg1 = jsonObject.getString("msg");
                    msg.obj = msg1;
                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    private void sharedata() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/index/makeScore";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("score", "1");//可不传
        paramsMap.put("type", "2");
        MyLog.e("分享得内容", token + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    title = data.getString("title");
                    desc = data.getString("desc");
                    msg.arg1 = 31;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public void changeUserLogo() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                ActivityCompat.requestPermissions(WebviewActivity.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA}, 10);
            } else {
                doUpFile();
            }
        } else {
            doUpFile();
        }
    }

    private void doUpFile() {

        final CharSequence[] items = {"相册", "拍照", "取消"};
        AlertDialog dlg = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.AlertDialogCustom)).setTitle("选择图片").setItems(items,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        //这里item是根据选择的方式，        在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
                        if (item == 1) {
                                            /* Intent getImageByCamera= new Intent("android.media.action.IMAGE_CAPTURE");
                                                     startActivityForResult(getImageByCamera, 1);   */
                            if (Build.VERSION.SDK_INT >= 24) {
                                try {
                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                                    File path = null;
                                    if (hasSdcard()) {
                                        path = Environment.getExternalStoragePublicDirectory(
                                                Environment.DIRECTORY_DCIM);

                                    }
                                    Date date = new Date();
                                    String timeStamp = getTime(date, "yyyyMMdd_HHmmss", Locale.CHINA);
                                    String imageFileName = "Camera/" + "IMGb_" + timeStamp + ".jpg";
                                    File image = new File(path, imageFileName);
                                    photoUri = FileProvider.getUriForFile(WebviewActivity.this, "com.xiaochun.hxhj.fileprovider", image);
                                    List resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                                    if (resInfoList.size() == 0) {
                                        ToastUtils.show("没有合适的相机应用程序");
                                        return;
                                    }
                                    Iterator resInfoIterator = resInfoList.iterator();
                                    while (resInfoIterator.hasNext()) {
                                        ResolveInfo resolveInfo = (ResolveInfo) resInfoIterator.next();
                                        String packageName = resolveInfo.activityInfo.packageName;
                                        grantUriPermission(packageName, photoUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                    }

                                    ContentValues values = new ContentValues();
                                    values.put(MediaStore.Audio.Media.TITLE, imageFileName);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                    startActivityForResult(intent, 1);
                                } catch (Exception e) {
                                    dialog.dismiss();
                                }
                            } else {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                                        "yyyy_MM_dd_HH_mm_ss");
                                String filename = timeStampFormat.format(new Date());
                                ContentValues values = new ContentValues();
                                values.put(MediaStore.Audio.Media.TITLE, filename);
                                photoUri = getContentResolver().insert(
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                                startActivityForResult(intent, 1);
                            }


                        } else if (item == 0) {
                            Intent getImage;
                            if (Build.VERSION.SDK_INT < 19) {
                                getImage = new Intent(Intent.ACTION_GET_CONTENT);
                                getImage.setType("image/*");
                                startActivityForResult(getImage, 0);
                            } else if (Build.VERSION.SDK_INT >= 24) {
                                // photo_image = createPublicImageFile();
                                try {
                                    File file = createPublicImageFile();
                                    Uri uri = FileProvider.getUriForFile(WebviewActivity.this, "com.xiaochun.hxhj.fileprovider", file);
                                    getImage = new Intent(Intent.ACTION_PICK, uri);
                                    startActivityForResult(getImage, 0);
                                } catch (Exception e) {
                                    dialog.dismiss();
                                }


                            } else {
                                getImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                startActivityForResult(getImage, 0);
                            }


                        } else {
                            dialog.dismiss();
                        }
                    }

                }).create();
        dlg.show();


    }

    public static boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    private String getTime(Date date, String mode, Locale locale) {
        SimpleDateFormat format = new SimpleDateFormat(mode, locale);
        return format.format(date);
    }

    private File createPublicImageFile() throws IOException {
        File path = null;
        if (hasSdcard()) {
            path = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM);
        }
        Date date = new Date();
        String timeStamp = getTime(date, "yyyyMMdd_HHmmss", Locale.CHINA);
        String imageFileName = "Camera/" + "IMG_" + timeStamp + ".jpg";
        File image = new File(path, imageFileName);
        //  mPublicPhotoPath = image.getAbsolutePath();
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ContentResolver resolver = getContentResolver();
        Log.e(">>>>>>>>>>>>>>", "拍照返回" + requestCode);

        /*if (requestCode == MyApp.Login_REQUEST_Code) {
            if (resultCode == MyApp.Result_SUCC_Code) {
				*//*ll_nologin.removeAllViews();
				onCreate(savedInstanceState);*//*
                Intent intent = new Intent(MyuserActivity.this, UserCenterActivity2.class);
                startActivity(intent);
            }

        }
*/
        switch (requestCode) {
            // 如果是直接从相册获取
            case 0:
//                Log.e("com.bangk.yh", "fanhuicuowu"+data.toString() + requestCode);
                if (data != null && data.getData() != null) {
                    startPhotoZoom(data.getData());
                    MyLog.e("com.bangk.yh", "3333333333" + data.getData() + "    " + requestCode);
                }
                break;
            // 如果是调用相机拍照时
            case 1:
//                Log.e("com.bangk.yh", "如果是调用相机拍照时1111"+data.toString() + requestCode);
                MyLog.e("相机返回", resultCode + "  相机");
                if (resultCode != Activity.RESULT_CANCELED) {

                    if (null != data && data.getData() != null) {
                        startPhotoZoom(data.getData());
                    } else {
                        if (photoUri != null) {
                            startPhotoZoom(photoUri);
                        }
                    }
                }

                break;

            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */


                if (photoUricat != null) {

                    Log.e("----------------", "xxxxxxxxxxx");
//                    Util.dismisDialog();
                    System.out.println("上传裁剪图片");

                    // Bundle extras = data.getExtras();
                    Bitmap myBitmap = null;
                    try {
                        myBitmap = getThumbnail(photoUricat, DensityUtil.dp(context, 150), DensityUtil.dp(context, 150));
                    } catch (Exception e) {
                        myBitmap = null;
                        Log.e("com.bangk.yh", "tttttttttttttttttttttttttt" + e.getMessage().toString());
                        e.printStackTrace();
                    }
                    if (myBitmap == null) {
                        Log.e("com.bangk.yh", "tingzhi" + photoUricat.toString());
                        break;
                    }
                    // Bitmap	myBitmap = getSmallBitmap(picPath);

                     /*
                    Bundle extras = data.getExtras();
                    Bitmap myBitmap = (Bitmap) extras.get("data"); */
                    FileOutputStream fileOutputStream = null;

                    try {
                        // 获取 SD 卡根目录
                        String saveDir = Environment.getExternalStorageDirectory() + "/meitian_photos";
                        // 新建目录
                        File dir = new File(saveDir);
                        if (!dir.exists()) dir.mkdir();
                        // 生成文件名
                        SimpleDateFormat t = new SimpleDateFormat("yyyyMMddssSSS");
                        String filename = "MT" + (t.format(new Date())) + ".jpg";
                        // 新建文件
                        File file = new File(saveDir, filename);
                        // 打开文件输出流
                        fileOutputStream = new FileOutputStream(file);
                        // 生成图片文件
                        myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                        // 相片的完整路径
                        UppicPath = file.getPath();
                        is_shot = true;
                        imgFile = file;

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (fileOutputStream != null) {
                            try {
                                fileOutputStream.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    System.out.println("选择相片路径:" + UppicPath);
                    if (UppicPath == null) {

                    } else {
//                        Util.showDialog(context, getString(R.string.upload_img), getString(R.string.please_wait));
                        uploadFile();
                        /*String httpUrl =myapp.getWebConfig() + "/api/common/upload";
                        String sssss = UploadUtil.uploadFile(imgFile,httpUrl);
                        System.out.println("选择相片路径:" + sssss);*/
                    }


                }
                break;

            case 4:

                Log.e("fjdosflkjsdfjsdolf", "changename");


                break;
            case 11:
                if (!islogin) {
                    islogin = true;
                    sharedPreferences.edit().putString("token", "").commit();
                    Intent intent = new Intent(context, LoginActivity.class);
                    context.startActivity(intent);
                    myapp.destoryActivity("主页面");
                }
                break;
            default:

                break;


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean islogin = false;

    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        photoUricat = null;
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Log.e("com.bangk.yh", uri.toString() + "xxxxxxxxxx");

            // Log.e("com.bangk.yh",url+"xxxxxxbbbbbbxxxx");
            if (Build.VERSION.SDK_INT >= 24) {
                //    String url = getPath(context, uri);
                //  Log.e("com.bangk.yh", file);
                //     File file = new File(url);
                //  Uri uri2 = FileProvider.getUriForFile(MyuserActivity.this, "com.example.m6wmr.fileprovider", uri);


                //  mFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/jd_id_origin_pictrue.jpg");
                //  mUri = FileProvider.getUriForFile(this, "com.zera.hello", mFile);
                /*
                try{

                    File file =  createPublicImageFile();
                    photoUricat = FileProvider.getUriForFile(MyuserActivity.this, "com.example.m6wmr.fileprovider", file);
                    intent.setDataAndType(uri, "image/*");
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    intent.putExtra("return-data", false);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

                    //photoUricat
                }catch (Exception e){
                    return;
                } */
                //    String url = getPath(context, uri);
                try {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.setDataAndType(uri, "image/*");
                    File file = createPublicImageFile();
                    //  photoUricat = FileProvider.getUriForFile(MyuserActivity.this, "com.example.m6wmr.fileprovider", file);


                    Log.e("com.bangk.yh", uri.toString() + "xxxxxx24");


                    photoUricat = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
                    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                } catch (Exception e) {
                    return;
                }


            } else {
                String url = getPath(context, uri);
                intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
                photoUricat = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
                intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

            }
        } else {
            intent.setDataAndType(uri, "image/*");
            photoUricat = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUricat);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        }


        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别


        //   photoUri = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        // intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        //intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());//
        startActivityForResult(intent, 3);
    }

    public Bitmap getThumbnail(Uri uri, int reqWidth, int reqHeight) throws IOException {
        InputStream input = getContentResolver().openInputStream(uri);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, options);
        if ((options.outWidth == -1) || (options.outHeight == -1))
            return null;
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        input.close();
        input = getContentResolver().openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
        input.close();
        return bitmap;
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }
        return inSampleSize;
    }

    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    // 上传图片
    private boolean uploadFile() {
        new Thread() {
            public void run() {
                super.run();

                Message msg = new Message();
                String end = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                try {
                    String httpUrl = myapp.getWebConfig() + "/api/common/upload";//
                    Log.e("xxx", httpUrl);
                    System.out.println("文件名-" + getFileName(UppicPath));
                    System.out.println("提交连接-" + httpUrl);
                    URL url = new URL(httpUrl);


                    HttpURLConnection con = (HttpURLConnection) url
                            .openConnection();
                    /* 允许Input、Output，不使用Cache */
                    con.setDoInput(true);
                    con.setDoOutput(true);
                    con.setUseCaches(false);
                    /* 设置传送的method=POST */
                    con.setRequestMethod("POST");
                    /* setRequestProperty */
                    con.setRequestProperty("Connection", "Keep-Alive");
                    con.setRequestProperty("Charset", "UTF-8");
                    con.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);

                    /* 设置DataOutputStream */
                    DataOutputStream ds = new DataOutputStream(
                            con.getOutputStream());
                    ds.writeBytes(twoHyphens + boundary + end);
                    ds.writeBytes("Content-Disposition: form-data; "
                            + "name=\"file\";filename=\""
                            + imgFile.getName() + "\"" + end);
//                            + getFileName(UppicPath) + ".jpg" + "\"" + end);
                    ds.writeBytes(end);
                    /* 取得文件的FileInputStream */
                    FileInputStream fStream = new FileInputStream(UppicPath);
                    /* 设置每次写入1024bytes */
                    int bufferSize = 1024;
                    byte[] buffer = new byte[bufferSize];
                    int length = -1;
                    /* 从文件读取数据至缓冲区 */
                    while ((length = fStream.read(buffer)) != -1) {
                        /* 将资料写入DataOutputStream中 */
                        ds.write(buffer, 0, length);
                    }
                    ds.writeBytes(end);
                    ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
                    /* close streams */
                    fStream.close();
                    ds.flush();
                    /* 取得Response内容 */
                    InputStream is = con.getInputStream();
                    int ch;
                    StringBuffer b = new StringBuffer();
                    while ((ch = is.read()) != -1) {
                        b.append((char) ch);
                    }
                    /* 将Response显示于Dialog */
                    // showDialog("上传成功"+b.toString().trim());

                    System.out.println("返回数据-" + b.toString().trim());
                    String backstrl = b.toString().trim();

                    /* 关闭DataOutputStream */
                    ds.close();
//                    Util.dismisDialog();
                    if (is_shot == true) {
                        //调用删除图片
                        File file = new File(UppicPath);
                        file.delete();
//							System.out.println("删除图片");
                    }


                    try {

                        JSONObject json = new JSONObject(backstrl);
                        Log.d("xxx", backstrl);

                        if (json.getString("code").equals("0")) {
                            msg.obj = json.getString("msg");
                            msg.arg1 = 0;
                            handler.sendMessage(msg);
                            return;
                        }
                        /*if (json.isNull("msg")) {

                            msg.arg1 = 1;
                            handler.sendMessage(msg);
                            return;
                        }*/

                        JSONObject backdata = json.getJSONObject("data");

                        msg.obj = backdata.getString("url");
                        msg.arg1 = 5;
                        handler.sendMessage(msg);
                        return;
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block

                        e.printStackTrace();

                        msg.arg1 = 1;
                        handler.sendMessage(msg);
                        return;
                    }

                } catch (Exception e) {
//                    Util.dismisDialog();

                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                    return;
                }

            }

            public synchronized void start() {
                super.start();
            }
        }.start();
        return false;
    }

    public String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }

    }

    /**
     * 修改头像
     */
    private void uploadnick(String imageurl) {
        String url = myapp.getWebConfig() + "/api/user/change_avatar";
        HashMap<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("token", token);
        paramsMap.put("avatar", imageurl);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    String imgurl = jsonObject.getString("data");

                    msg.obj = imgurl;
                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                Log.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 授权回调函数
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 10:
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 获取到权限，作相应处理
                        doUpFile();
                    } else {
                        // 没有获取到权限，做特殊处理
                        showPermissionDialog();
                    }
                } else {
                    showPermissionDialog();
                }
                break;
            default:
                break;
        }
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 提示打开设置对话框
     */
    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);


        builder.setTitle("帮助");
        builder.setMessage("当前应用需要读手机存储和信息权限。请点击\"设置\"-打开权限。");
        // 拒绝, 退出应用
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });


        builder.setCancelable(false);
        builder.show();
    }


}
